import {
  ValueOP,
  ISearchCond,
  ITreeNodeData,
  TreeController,
  ISearchCondField,
  ToolbarController,
  SearchBarController,
  SearchFormController,
} from '@ibiz-template/runtime';
import { IDESearchForm, IDEToolbar, ISearchBar } from '@ibiz/model-core';

/**
 * @description 资源排程树控制器
 * @export
 * @class ResourceScheduleTreeController
 * @extends {TreeController}
 */
export class ResourceScheduleTreeController extends TreeController {
  /**
   * @description 工具栏模型
   * @readonly
   * @type {(IDEToolbar | undefined)}
   * @memberof ResourceScheduleTreeController
   */
  get toolbarModel(): IDEToolbar | undefined {
    const toolbarModel = this.view.model.viewLayoutPanel?.controls?.find(
      ctrl => ctrl.name === `${this.model.name}toolbar`,
    );
    if (toolbarModel)
      return {
        ...toolbarModel,
        xdataControlName: this.model.name,
      };
    return;
  }

  /**
   * @description 搜索栏模型
   * @readonly
   * @type {(ISearchBar | undefined)}
   * @memberof ResourceScheduleTreeController
   */
  get searchBarModel(): ISearchBar | undefined {
    return this.view.model.viewLayoutPanel?.controls?.find(
      ctrl => ctrl.name === `${this.model.name}searchbar`,
    );
  }

  /**
   * @description 搜索表单模型
   * @readonly
   * @type {(IDESearchForm | undefined)}
   * @memberof ResourceScheduleTreeController
   */
  get searchFormModel(): IDESearchForm | undefined {
    return this.view.model.viewLayoutPanel?.controls?.find(
      ctrl => ctrl.name === `${this.model.name}searchform`,
    );
  }

  /**
   * @description 工具栏
   * @readonly
   * @type {(ToolbarController | undefined)}
   * @memberof ResourceScheduleTreeController
   */
  get toolbar(): ToolbarController | undefined {
    if (this.toolbarModel)
      return this.view.getController(
        this.toolbarModel.name!,
      ) as ToolbarController;
    return;
  }

  /**
   * @description 搜索栏
   * @readonly
   * @type {(SearchBarController | undefined)}
   * @memberof ResourceScheduleTreeController
   */
  get searchBar(): SearchBarController | undefined {
    if (this.searchBarModel)
      return this.view.getController(
        this.searchBarModel.name!,
      ) as SearchBarController;
    return;
  }

  /**
   * @description 搜索表单
   * @readonly
   * @type {(SearchFormController | undefined)}
   * @memberof ResourceScheduleTreeController
   */
  get searchForm(): SearchFormController | undefined {
    if (this.searchFormModel)
      return this.view.getController(
        this.searchFormModel.name!,
      ) as SearchFormController;
    return;
  }

  /**
   * @description 获取搜索表单参数
   * @returns {*}  {(ISearchCond[] | undefined)}
   * @memberof ResourceScheduleTreeController
   */
  getSearchFormParams(): ISearchCond[] | undefined {
    if (!this.searchForm) return;
    const params = this.searchForm.getFilterParams();
    const valueOPs: string[] = [];
    for (const key in ValueOP) {
      if (key !== ValueOP.EXISTS && key !== ValueOP.NOT_EXISTS) {
        const value = ValueOP[key as keyof typeof ValueOP];
        valueOPs.push(value);
      }
    }
    const searchconds: ISearchCondField[] = [];
    Object.keys(params).forEach(key => {
      const value = params[key];
      const tempKey = key.toLocaleUpperCase();
      let fieldname = '';

      // 检查键是否以'N_'开头
      const condop = valueOPs.find(filter => tempKey.endsWith(`_${filter}`));
      if (tempKey.startsWith('N_') && condop) {
        // 去除'N_'前缀与条件后缀
        fieldname = key.slice(2).slice(0, -`_${condop}`.length);
        if (fieldname && condop)
          searchconds.push({
            condtype: 'DEFIELD',
            fieldname,
            value,
            condop: condop.toLocaleUpperCase() as ValueOP,
          });
      }
    });
    if (searchconds.length)
      return [
        {
          searchconds,
          condop: 'AND',
          condtype: 'GROUP',
        },
      ];
    return;
  }

  /**
   * @description 获取过滤参数
   * @param {IParams} [extraParams]
   * @returns {*}  {Promise<IParams>}
   * @memberof ResourceScheduleTreeController
   */
  async getFetchParams(extraParams?: IParams): Promise<IParams> {
    const params = await super.getFetchParams(extraParams);
    if (this.searchBar) {
      if (this.searchBar.state.query && !params.query)
        params.query = this.searchBar.state.query;
      Object.assign(params, this.searchBar.getFilterParams());
    }
    const searchconds = this.getSearchFormParams();
    if (searchconds) {
      if (params.searchconds && params.searchconds.length > 0) {
        params.searchconds = [
          {
            condop: 'AND',
            condtype: 'GROUP',
            searchconds: [...params.searchconds, ...searchconds],
          },
        ]
      } else {
        params.searchconds = searchconds;
      }
    }
    return params;
  }

  /**
   * @description 设置选中改变
   * @param {ITreeNodeData[]} selection
   * @memberof ResourceScheduleTreeController
   */
  setSelection(selection: ITreeNodeData[]): void {
    super.setSelection(selection);
    const node = selection?.[0];
    const nodeModel = this.getNodeModel(node._nodeId);
    this.toolbar?.calcButtonState(node, nodeModel?.appDataEntityId, {
      view: this.view,
      ctrl: this,
    });
  }
}
